package com.qyh.lucas.configuration;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qyh.lucas.model.Fsm;
import org.apache.commons.io.IOUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

@EnableConfigurationProperties(LucasConfigurationProperties.class)
public class LucasConfiguration {
    @Bean
    public Fsm fsm(LucasConfigurationProperties lucasConfigurationProperties) throws IOException {
        List<LucasConfigurationProperties.Config> configs = lucasConfigurationProperties.getConfig();
        LucasConfigurationProperties.Config config = configs.get(0);
        String name = config.getName();
        String fileName = config.getFileName();

        ClassPathResource classPathResource = new ClassPathResource(fileName);
        InputStream inputStream = classPathResource.getInputStream();
        String json = IOUtils.toString(new InputStreamReader(inputStream));

        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(json, new TypeReference<Fsm>() {
        });
    }
}
